
/*音乐列表菜单的函数定义*/
#include "listmenu.h"
#include "download_list.h"
#include "generalsetstyle.h"
#include "musicinfo.h"
#include <QFormLayout>
#include <QInputDialog>
#include <QLabel>
#include <QMenu>
#include <QMessageBox>
#include <QToolTip>
#include <QClipboard>
#include <QTextBrowser>
#include <QDesktopServices>
#include <QUrl>


void MainWindow::SetListMenu(QString DirPath) {
  MainWindow *parent = this;
  qDebug() << DirPath;
  QTableView *song_list=custom_song_list;
  ui->music_list->setContextMenuPolicy(Qt::CustomContextMenu);
  QTableView *tableview = ui->music_list;
  disconnect(tableview, &QTableView::customContextMenuRequested, nullptr,
             nullptr);
  QObject::connect(tableview, &QListWidget::customContextMenuRequested,
                   [tableview, DirPath, parent, this,song_list](const QPoint &pos) {
                     // 获取点击位置的项目
                     CustomMenu(tableview, pos, DirPath, parent,ui,song_list);
                   });
}

void CustomMenu(QTableView *tableview, const QPoint &pos, QString DirPath,
                MainWindow *parent,Ui::MainWindow *ui,QTableView *song_list)
{
    int currentRow = tableview->rowAt(pos.y());
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(tableview->model());
    QStandardItem *Item =model->item(currentRow,0);//一开始是0

  if (!Item)
    return; // 如果点击空白处则不显示菜单

  // 创建右键菜单
  QMenu menu;
  menu.setToolTipsVisible(true);

  // 添加菜单项
  QAction *copyTextAction = menu.addAction(QIcon(":/icons/复制.png"),"复制歌曲名称");
  QPixmap pixmap(":/icons/复制.png");
  QAction *songInfoAction = menu.addAction(QIcon(":/icons/信息.png"),"显示歌曲信息");
  QAction *loadListAction = menu.addAction(QIcon(":/icons/添加下一首.png"),"下一首播放");
  menu.addSeparator(); // 分割线
  QAction *downloadAction = menu.addAction(QIcon(":/icons/下载.png"),"下载");
  QAction *fileDirAction = menu.addAction(QIcon(":/icons/文件夹.png"),"打开文件所在路径");
  QAction *customlistAction = menu.addAction(QIcon(":/icons/添加.png"),"添加到...");
  QAction *deleteAction = menu.addAction(QIcon(":/icons/删除.png"),"删除");
  //显示菜单并获取用户选择
  QAction *selectedAction = menu.exec(tableview->viewport()->mapToGlobal(pos));
  //打开文件所在路径
  if(selectedAction==fileDirAction)
  {
      OpenFileDir(tableview, DirPath,currentRow);
  }
  //查看歌曲信息
  else if(selectedAction==songInfoAction)
  {
      ShowSongInfo(tableview, DirPath,parent,currentRow);
  }
  //添加到下一首播放操作
  else if(selectedAction==loadListAction)
  {
      LoadListPlay(tableview,song_list,currentRow);
  }
  //下载功能
  else if(selectedAction==downloadAction)
  {
      DownLoadSong(tableview, DirPath, parent,ui,currentRow);
  }
  //复制歌曲名称
  else if(selectedAction==copyTextAction)
  {
      CopySongName(tableview,parent,currentRow);
  }
  //添加到自定义歌单
  else if (selectedAction == customlistAction) {

    // 添加到自定义列表
    CustomSongsList(tableview, DirPath, parent,currentRow);
  }
   // 删除操作
  else if (selectedAction == deleteAction) {
      // 删除项目
      //删除的时候显示需再次确认的对话框
      QDialog dialog(parent);
      QVBoxLayout layout(&dialog);
      QLabel label("您确定要执行此操作吗？");
      layout.addWidget(&label);
      QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
      layout.addWidget(&buttonBox);
      QObject::connect(&buttonBox, &QDialogButtonBox::accepted, [&dialog, tableview, DirPath, parent, pos]() {
          int currentRow = tableview->rowAt(pos.y());
          //获取模型
          QStandardItemModel* model = qobject_cast<QStandardItemModel*>(tableview->model());
          QStandardItem *removedItem =model->item(currentRow,0);//一开始是0
          qDebug()<<removedItem->toolTip();
          DeleteSong(tableview, DirPath, parent,true,currentRow);
          model->removeRow(currentRow);
          dialog.accept();
      });
      QObject::connect(&buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
      dialog.setWindowFlag(Qt::FramelessWindowHint, true);
      dialog.adjustSize();
      dialog.exec();
  }
}

void DeleteSong(QTableView *tableview, QString DirPath,
                MainWindow *parent,bool isNotCollect,int currentRow)
{
    QString dir_target_name;

    //获取模型
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(tableview->model());
    QStandardItem *item =model->item(currentRow,0);//一开始是

    qDebug()<<currentRow;
    QString musicName =item->toolTip();
     qDebug()<<"要删除的歌曲名称"<<musicName;
    //qDebug()<<
    //是不是收藏操作
    if (!isNotCollect)//是
    {

        //如果在收藏目录下
        dir_target_name=QDir::currentPath()+QDir::separator()+"我的收藏";
        if(dir_target_name==DirPath)
        {
            int index=tableview->currentIndex().row();
            tableview->model()->removeRow(currentRow);
            tableview->selectRow(index);
        }


    }
    else//不是
    {
      dir_target_name=DirPath;
    }
    qDebug()<<dir_target_name;
    QString musicAbsPath = dir_target_name+ QDir::separator()+musicName+".mp3";
    QString musicLyricsPath =dir_target_name+QDir::separator()+musicName +".lrc";
    qDebug()<<"删除的文件"<<musicAbsPath<<musicLyricsPath;

    if(DeleteFile(musicAbsPath)&& DeleteFile(musicLyricsPath) )//删除歌曲
    {

    }

}
//添加歌曲到歌单的选项
bool CollectSelect(QTableView *tableview, QString DirPath,
                   MainWindow *parent, bool isNotCollect,
                   QString target_list,int currentRow)
{

    //获取模型
  QStandardItemModel* model = qobject_cast<QStandardItemModel*>(tableview->model());
  QStandardItem *Item =model->item(currentRow,0);//一开始是0
  QString dir_target_name;
  //如果是收藏操作
  if (!isNotCollect)
  {
    dir_target_name = "我的收藏";
    Mkdir(dir_target_name, parent);
  }
  else
  {
    dir_target_name = target_list;
  }
  // 音乐源文件路径
  QString musicName = Item->toolTip();
  qDebug()<<musicName;
  QString musicAbsPath = DirPath + QDir::separator() + musicName + ".mp3";
  QString musicLyricsPath = DirPath + QDir::separator() + musicName + ".lrc";

  // 目标文件路径 dir_name="我的收藏"(相对路径);
  QString targetmusicPath =
      dir_target_name + QDir::separator() + musicName + ".mp3";
  QString targetlyricsPath =
      dir_target_name + QDir::separator() + musicName + ".lrc";


  // 添加前先进行判断
  if (!QFile::exists(musicAbsPath) && !QFile::exists(musicLyricsPath)) {
    qWarning() << "音乐源文件不存在:" << musicAbsPath;
    qWarning() << "歌词源文件不存在:" << musicLyricsPath;
  } else {
    qDebug() << "源文件存在:" << musicAbsPath;
  }
  // 文件添加操作
  if (QFile::copy(musicAbsPath,targetmusicPath) && QFile::copy(musicLyricsPath, targetlyricsPath))
  {
     qDebug()<<targetmusicPath<<"+++++++++++++++++++++++++";
    qDebug() << musicAbsPath << ">>" << targetmusicPath << Qt::endl;
    qDebug() << musicLyricsPath << ">>" << targetlyricsPath << Qt::endl;
    if(isNotCollect==true)
        QMessageBox::information(parent, "弹窗", "已添加成功");
    return true;
  }
  else
  {
    if (QFile::exists(targetmusicPath) && QFile::exists(targetlyricsPath))
    {
        if(isNotCollect==true)
        {
            QMessageBox::information(parent, "弹窗", "文件已经添加过了");

        }
        else
            qDebug()<<"收藏成功";
        return false;

    }

  }
}

void CustomSongsList(QTableView *tableview, QString DirPath,MainWindow *parent,int currentRow)
{
    //获取模型
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(tableview->model());
    QStandardItem *Item =model->item(currentRow,0);//一开始是0
  //打开歌单
  QDialog dialog(parent);
  dialog.setWindowTitle("添加"+Item->text()+"到"); // 设置弹窗名称
  QGridLayout *gridLayout = new QGridLayout(&dialog);
  // 歌单列表
  MusicListUpdate(gridLayout, tableview, DirPath, parent,currentRow);
  QPushButton *newaddBtn = new QPushButton("➕新建歌单");
  gridLayout->addWidget(newaddBtn);
  // 新建歌单的信号
  MainWindow::connect(
      newaddBtn, &QPushButton::clicked,
      [parent, DirPath, gridLayout, tableview, newaddBtn, currentRow]() {
        bool ok;
        QString newlist = QInputDialog::getText(parent,       // 父窗口
                                                "输入框标题", // 窗口标题
                                                "歌单名称:",  // 提示标签文本
                                                QLineEdit::Normal, // 输入模式
                                                "新建歌单...",     // 初始文本
                                                &ok // 接收确定/取消状态
        );
        //避免无效更新
        if(!newlist.isNull())
        {
            Mkdir(newlist, parent);
            MusicListUpdate(gridLayout, tableview, DirPath, parent,currentRow);
            gridLayout->addWidget(newaddBtn);
        }

      });
  dialog.adjustSize();
  dialog.setObjectName("adasd");
  dialog.setMinimumWidth(300);
  dialog.exec();
}

void Mkdir(QString dir_name, MainWindow *parent) {
  QDir dir;
  //判断目录是否存在,不存在就创建
  if (!dir.exists(dir_name) && dir_name != "") {
    if (dir.mkdir(dir_name)) {
      qDebug() << "目录创建成功";
      //isListHave = true;
      QMessageBox::information(parent, "这是一个弹窗",
                               "歌单已创建                 ");
      // QToolTip::showText(QCursor::pos(), "随机模式", nullptr, QRect(), 2000);

    } else {
      qDebug() << "目录创建失败，可能因为："
               << "1. 父目录不存在\n"
               << "2. 目录已存在\n"
               << "3. 权限不足";
    }
  }
  else if(dir.exists(dir_name) && dir_name != "我的收藏")
  {
    qDebug() << "目录已经存在,无需再创建";
    QMessageBox::information(parent, "", "目录已经存在,无需再创建");
    //isListHave = false;
  }

}

bool DeleteFile(QString filePath)
{
    if (QFile::exists(filePath)) {
        if (QFile::remove(filePath)) {
            qDebug() << "文件删除成功:" << filePath;
            return true;
        } else {
            qDebug() << "文件删除失败:" << filePath;
            return false;
        }
    } else {
        qDebug() << "文件不存在:" << filePath;
        return false;
    }
}

// 获取当前路径下所有的子目录(不递归)->歌单
QStringList MainWindow::MusicList()
{
  QDir dir(QDir::currentPath());
  dir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
  QStringList dirNames = dir.entryList();
  // for(int i=0;i<dirNames.count();i++)
  //     if(dirNames[i]=="我的收藏")
  //         dirNames.removeAt(i);
  return dirNames; // QStringList 自动管理内存
}

void MusicListUpdate(QGridLayout *gridLayout, QTableView *tableview,
                     QString DirPath,
                     MainWindow *parent,int currentRow)
{
  QStringList music_list = MainWindow::MusicList();
  for(int i=0;i<music_list.count();i++)
        if(music_list[i]=="我的收藏")
        {
            music_list.removeAt(i);
            break;
        }
  int count = music_list.count();
  qDebug() << "count=" << count;
  // 批量创建按钮
  QList<QPushButton *> buttons;

  // 排列分布
  int row = 0, column = 0;
  for (int i = 0; i < count; ++i) {
    QPushButton *btn = new QPushButton(QString(music_list[i]).arg(i));
    buttons.append(btn);
    // gridLayout->addWidget(btn,0,i);
    if (column > 2) {
      row += 1;
      column = 0;
    }
    gridLayout->addWidget(btn, row, column);
    column++;
  }
  QStandardItemModel* model = qobject_cast<QStandardItemModel*>(tableview->model());
  QStandardItem *Item =model->item(currentRow,0);//一开始是0
  QString musicName = Item->toolTip();
  //每个按钮都添加事件
  for (int i = 0; i < count; i++)
  {
      //查看其他歌单有无该音乐
      QString musicAbsPath = QDir::currentPath()
                             +QDir::separator()+music_list[i]
                             +QDir::separator()+musicName + ".mp3";
      qDebug()<<musicAbsPath;
      if(QFile::exists(musicAbsPath))
      {
          qDebug()<<"有该歌曲";
          buttons[i]->setDisabled(true);
          buttons[i]->setToolTip("该歌曲已经添加过了");
      }


    MainWindow::connect(
        buttons[i], &QPushButton::clicked,
        [DirPath, parent, tableview, music_list, buttons, i, currentRow]() {
          QString target_list = music_list[i];
          //添加到歌单的功能
          CollectSelect(tableview, DirPath,parent, true, target_list,currentRow);
          buttons[i]->setDisabled(true);
          buttons[i]->setToolTip("该歌曲已经添加过了");
    });
  }
}

//下载歌曲
void DownLoadSong(QTableView *tableview,QString DirPath,MainWindow *parent,Ui::MainWindow *ui,int currentRow)
{
    qDebug()<<currentRow<<"------------";
    //获取模型
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(tableview->model());
    QStandardItem *Item =model->item(currentRow,0);//一开始是0

    QString dir_target_name = QFileDialog::getExistingDirectory(
        parent,                 // 父窗口
        "选择下载路径", // 对话框标题
        QDir::currentPath(),  // 默认打开路径
        QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    //音乐源文件路径
    if(!dir_target_name.isNull())
    {

        QString musicName = Item->toolTip();
        QString musicAbsPath = DirPath + QDir::separator() + musicName + ".mp3";
        QString musicLyricsPath = DirPath + QDir::separator() + musicName + ".lrc";
        QString targetmusicPath;
        QString targetlyricsPath;
        targetmusicPath =
            dir_target_name + QDir::separator() + musicName + ".mp3";
        targetlyricsPath =
            dir_target_name + QDir::separator() + musicName + ".lrc";

        if (QFile::copy(musicAbsPath, targetmusicPath) &&
            QFile::copy(musicLyricsPath, targetlyricsPath))
        {
            QMessageBox::information(parent, "弹窗", "下载成功");
            //以下载音乐文件列表
            qDebug()<<dir_target_name;
            DownLoadList(tableview,ui,DirPath,parent,dir_target_name,currentRow);
        }
        else
            QMessageBox::information(parent, "弹窗", "下载失败");

    }


}
//获取歌曲名称
void CopySongName(QTableView *tableview,MainWindow *parent,int currentRow)
{
    //获取模型
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(tableview->model());
    QStandardItem *currentItem =model->item(currentRow,0);//一开始是0
    //QListWidgetItem *currentItem = listWidget->currentItem();

    if (currentItem)
    {
        // 获取文本
        QString title = currentItem->toolTip();
        // 获取剪贴板并设置文本
        QClipboard *clipboard = QApplication::clipboard();
        clipboard->setText(title);
        QMessageBox::information(parent, "", "复制成功:"+title);
    }

}

//查看歌曲信息
void ShowSongInfo(QTableView *tableview,QString DirPath,MainWindow *parent,int currentRow)
{
    //获取模型
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(tableview->model());
    QStandardItem *Item =model->item(currentRow,0);//一开始是0
    QString musicName = Item->toolTip();
    QString musicAbsPath = DirPath + QDir::separator() + musicName + ".mp3";
    //获取信息
    MainWindow::MusicMetaData metaData=getMusicData(musicAbsPath,true);
    QDialog dialog(parent);
    QTextBrowser songinfo(&dialog);

    songinfo.setStyleSheet(R"(
                            QTextBrowser
                            {
                                background-color: transparent;
                            })");

    QTextDocument *document = songinfo.document();

    // 获取光标并移动到文档末尾
    QTextCursor cursor = songinfo.textCursor();
    cursor.movePosition(QTextCursor::End);

    // 创建唯一的资源名称（可以使用UUID或时间戳）
    QString imageName = QString("image_%1").arg(QDateTime::currentMSecsSinceEpoch());

    // 将 QImage 添加到文档资源中
    document->addResource(QTextDocument::ImageResource, QUrl(imageName), QVariant(metaData.image));
    // 创建图片格式并设置资源名称
    QTextImageFormat imageFormat;
    imageFormat.setName(imageName);
    imageFormat.setWidth(200);
    imageFormat.setHeight(200);
    cursor.insertImage(imageFormat);
    songinfo.adjustSize();
    // 可选：在图片后添加换行
    cursor.insertText("\n");

    // 可选：设置图片大小
    // imageFormat.setWidth(desiredWidth);
    // imageFormat.setHeight(desiredHeight);

    // 插入图片
    songinfo.append("标题："+metaData.title);
    songinfo.append("作者："+metaData.author);
    songinfo.append("专辑："+metaData.albumTitle);
    songinfo.append("时长："+metaData.duration);
    songinfo.append("编码器："+metaData.codec_name);
    songinfo.append("采样器："+metaData.sample_rate);
    songinfo.append("比特率："+metaData.bit_rate);


    // dialog.setFixedWidth(150);
    // dialog.setMinimumHeight(300);
    songinfo.adjustSize();
    songinfo.setFixedHeight(songinfo.height()+200);
    dialog.setWindowTitle(musicName);
    dialog.exec();

}

//打开文件所在目录
void OpenFileDir(QTableView *tableview,QString DirPath,int currentRow)
{

    QDesktopServices::openUrl(QUrl::fromLocalFile(DirPath));
}


//加载待播放列表
void LoadListPlay(QTableView *tableview,QTableView *song_list,int currentRow)
{
    //获取播放列表模型
    int currentRow_parent = currentRow; // 获取行号
    LoadSongLayout(tableview,song_list,currentRow_parent);

}

void LoadSongLayout(QTableView *tableview,QTableView *song_list,int index)
{
    QStandardItemModel *model_parent = qobject_cast<QStandardItemModel*>(tableview->model());
    QStandardItemModel *model_son = qobject_cast<QStandardItemModel*>(song_list->model());
    //获取行号
    QModelIndex currentIndex_son = song_list->currentIndex();
    int newRow = currentIndex_son.row(); // 获取行号
    newRow++;
    model_son->insertRow(newRow);//添加一行
    //设置当前行
    QStandardItem *item_son =model_son->item(newRow,0);
    QStandardItem *item_parent =model_parent->item(index,0);
    if (!item_son) {
        item_son = new QStandardItem();
        model_son->setItem(newRow, 0, item_son);
    }
    item_son->setToolTip(item_parent->toolTip());
    item_son->setIcon(item_parent->icon());
    MainWindow::MusicMetaData musicdata;
    musicdata.title=item_parent->data(Qt::UserRole+0).toString();
    musicdata.author=item_parent->data(Qt::UserRole+1).toString();
    musicdata.albumTitle=item_parent->data(Qt::UserRole+2).toString();
    musicdata.duration=item_parent->data(Qt::UserRole+3).toString();
    musicdata.filepath=item_parent->data(Qt::UserRole+4).toString();
    QStringList musicinfo;
    musicinfo <<musicdata.title
              <<musicdata.author
              <<musicdata.albumTitle
              <<musicdata.duration
              <<musicdata.filepath;
    //可以从每个歌曲中获取“标题”等信息

    for(int i=0;i<musicinfo.count();i++)
    {
        item_son->setData(musicinfo[i],Qt::UserRole + i);
        qDebug()<<newRow<<item_son->data(Qt::UserRole + i).toString();
    }
    musicinfo.clear();
    musicinfo<<musicdata.title<<musicdata.duration;
    for(int i=1;i<model_son->columnCount()-1;i++)
    {
        item_son =model_son->item(newRow,i);
        if (!item_son) {
            item_son = new QStandardItem();
            model_son->setItem(newRow,i, item_son);
        }
        item_son->setText(musicinfo[i-1]);
        item_son->setToolTip(musicinfo[i-1]);
        item_son->setTextAlignment(Qt::AlignCenter);
    }
    QWidget *widget = new QWidget();
    // widget->setStyleSheet(  "QWidget {"
    //                       "   background-color: #1a6ceb;"
    //                       "}");
    QHBoxLayout *layout = new QHBoxLayout(widget);
    // 创建删除按钮
    QPushButton *delbtn = new QPushButton();
    GeneralSetButtonStyle(delbtn,":/icons/删除.png",25,"删除");
    delbtn->setContentsMargins(0, 0, 0, 20); // 下边距20像素
    layout->addWidget(delbtn);
    song_list->setIndexWidget(model_son->index(newRow, 3), widget);

    MainWindow::connect(delbtn, &QPushButton::clicked,[=]()
                        {
                            QModelIndex currentIndex_son = song_list->currentIndex();
                            int preindex = currentIndex_son.row(); // 获取行号
                            QPoint buttonPos = delbtn->mapTo(song_list,QPoint(0, 0));
                            int currentRow = song_list->rowAt(buttonPos.y());
                            if(currentRow==-1)
                                currentRow=song_list->model()->rowCount();
                            currentRow--;
                            model_son->removeRow(currentRow);
                            buttonPos = delbtn->mapTo(song_list->viewport(),QPoint(0, 0));
                            //如果说删除的是最后一行

                            if(preindex==song_list->model()->rowCount())
                            {

                                preindex--;
                                //buttonPos.setY(rect.y());
                            }
                            //如果删除的是正在播放的歌曲的上方
                            if(currentRow<preindex)
                            {
                                /*如果不让它等于-1,当播放歌曲处于第二行并且进行删除第一行的操作时就会导致
                                currentRow==song_list->currentIndex().row()从而触发鼠标点击操作*/
                                currentRow=-1;
                                preindex--;
                            }
                            //设置预先保存的行号以在视觉上达到没有更改行号的目的
                            song_list->selectRow(preindex);

                            //如果删除的歌曲恰好正在播放
                            //自动播放下一首

                            if(currentRow==song_list->currentIndex().row()
                                &&currentRow!=song_list->model()->rowCount())
                            {
                                //模拟鼠标双击事件,再次点击当前行的音乐

                                QPoint globalPos = song_list->mapToGlobal(buttonPos);
                                QMouseEvent pressEvent(QEvent::MouseButtonDblClick,
                                                       buttonPos,
                                                       globalPos,
                                                       Qt::LeftButton,
                                                       Qt::LeftButton,
                                                       Qt::NoModifier);
                                QMouseEvent releaseEvent(
                                    QEvent::MouseButtonRelease,      // 事件类型：鼠标释放
                                    buttonPos,
                                     globalPos,
                                    Qt::LeftButton,                  // 触发事件的按钮：左键
                                    Qt::NoButton,                    // 当前按下的按钮：无（因为已经释放）
                                    Qt::NoModifier                   // 键盘修饰键：无
                                    );
                                qDebug()<<"asdasda";
                                QApplication::sendEvent(song_list->viewport(), &pressEvent);
                                QApplication::sendEvent(song_list->viewport(), &releaseEvent);
                            }


                        });

}
